package controllers

import (
	"net/http"
	"github.com/gin-gonic/gin"
	"fmt"
	"hellow/model"
)

// 获取单个用户信息
func GetUserInfo(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusOK, gin.H{
			"errcode": 1,
			"errmsg":"param id is null",
			"data":"",
		})
		return
	}
	data,err := model.GetUserInfoById(id)
	if (err != "") {
		c.JSON(500, gin.H{
			"errcode":1,
			"errmsg":err,
			"data":data,
		})
		return
	}
    c.JSON(http.StatusOK, gin.H{
    	"errcode": 0,
		"errmsg": "success",
		"data":data,
    })	
    return
}

// 添加用户
func AddUser(c *gin.Context) {
	var userInfo model.User
	errs := c.ShouldBindQuery(&userInfo)
	if errs != nil {
		c.JSON(500, gin.H{
	        "errcode":  1,
	        "errmsg": "params is error:" + errs.Error(),
	        "data":"",
	    })
	    return
	}
	fmt.Println("params is ",userInfo)
	err := model.InsertUserInfo(userInfo.Username,userInfo.Age, userInfo.Createtime, userInfo.Password, userInfo.Phone)
	if err != "" {
    	c.JSON(500, gin.H{
    		"errcode": 1,
    		"errmsg" : err,
    		"data":"",
    	})
        return
    }	
    c.JSON(http.StatusOK, gin.H{
    	"errcode": 0,
    	"errmsg": "success",
    	"data":"",
    })
    return
}

type ParamUser struct {
	Username string `json:"username" form:"username"`
	Phone string `json:"phone" form:"phone"`
	Page int `json:"page" form:"page"`
}

func (p ParamUser) call() ParamUser {
	p.Page = p.Page * 10
	return p
}

// 列表
func GetUserList(c *gin.Context) {
	var param ParamUser
	// var userList []model.User
	err := c.ShouldBindQuery(&param)
	if err != nil {
		c.JSON(500, gin.H{
			"errcode": 1,
			"errmsg": err,
			"data": "",
		})
		return
	}
	param = param.call()
	fmt.Println(param)
	userList,errMsg := model.GetListByCondition(param.Username, param.Phone, param.Page)
	if errMsg != "" {
		c.JSON(500, gin.H{
    		"errcode": 1,
    		"errmsg" : errMsg,
    		"data":"",
    	})
    	return 
	}
	c.JSON(http.StatusOK, gin.H{
    	"errcode": 0,
    	"errmsg": userList,
    	"data":"",
    })
}

